import axios from 'axios'
import mpAdapter from 'axios-miniprogram-adapter'
import store from '../store/index.js'

axios.defaults.adapter = mpAdapter;
// 重试次数，共请求2次
axios.defaults.retry = 3
// 请求的间隙
axios.defaults.retryDelay = 1000
const http = axios.create({
	baseURL: "https://hilton-api.doradoar.com",
	//baseURL: "http://192.168.3.13:8082",
	timeout: 5000
});

http.interceptors.request.use(config => {
	const userToken = uni.getStorageSync("userToken");
	// console.log(userToken)
	const userInfo = store.state.userInfo;
	//如果有token 并且没有过期
	if (userToken !== null) {
		config.headers.Authorization = `Bearer ${userToken}`;
	}
	//如果没有获取过token
	// if (store.state.getUserToken === false) {
	// 	store.commit('setGetUserToken', true)
	// 	store.dispatch('login');
	// }
	// if (store.state.getMallConfig === false) {
	// 	store.commit('setGetMallConfig', true)
	// 	store.dispatch('getMallConfig');
	// }

	config.headers['X-Client-Type'] = `MINI_PROGRAM`;
	// if(userInfo === null && store.state.getUserInfo === false){
	// 	store.commit('setGetUserInfo', true)
	// 	store.dispatch('getUserInfo');
	// }
	// console.log(config)
	return config;
}, error => { //请求错误处理
	return Promise.reject(error);
});

http.interceptors.response.use(
	response => { //成功请求到数据
		if (response.data.code === 401) {
			let config = response.config;
			console.log('登录超时');
			uni.showToast({
				icon: "error",
				title: '请先登录',
				duration: 1000,
        complete: () => {
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/index/HiltonHotelPage' })
          }, 1000)
        },
			})
      
			// if (store.state.timeOutProcess === false) {
			// 	store.dispatch('login');
			// 	store.commit('setTimeOutProcess', true);
			// }
			// store.commit('setTokenInvalid', true);

			// //请求重试
			// config.__retryCount = config.__retryCount || 0;
			// if (config.__retryCount >= config.retry) {
			// 	// 返回错误并退出自动重试
			// 	return Promise.resolve(response.data);
			// }
			// config.__retryCount += 1;
			// // 创建新的Promise
			// var backoff = new Promise(function (resolve) {
			// 	setTimeout(function () {
			// 		resolve();
			// 	}, config.retryDelay || 1000);
			// });

			// 返回重试请求
			return backoff.then(function () {
				delete config.headers.Authorization;
				return http(config);
			});
		} else {
			return response.data;
		}
	},
	error => { //响应错误处理
		console.log('error');
		console.log(error);
		console.log(JSON.stringify(error));
		return Promise.reject(error);
	}
)
export default http;
